<template>
  <div v-loading.fullscreen.lock="viewLoading">
    <CrudView
      :form-data="formData"
      :form-items="formItems"
      :btn-items="btnItems"
      :page-colums="pageColums"
      :page-data="{pageInfo, list}"
      :selection-change-handler="selectionChangeHandler"
    />
    <!-- 学院信息编辑/新增模态框  -->
    <el-dialog
      :title="modalTitle"
      :center="true"
      :visible.sync="showModal"
      :before-close="closeModal"
    >
      <el-form :model="modalData" label-width="90px" :disabled="modalModel === 'Look'">
        <el-tabs v-model="activename">
          <el-tab-pane label="基本信息" name="first">
            <div style="max-height: 400px;overflow: auto">
              <el-form-item label="学院名称">
                <el-input v-model="modalData.collegeName" type="text" />
              </el-form-item>
              <el-form-item label="学院地址">
                <el-input v-model="modalData.address" type="text" />
              </el-form-item>
              <el-form-item label="学院电话">
                <el-input v-model="modalData.telNumber" type="text" />
              </el-form-item>
              <el-form-item label="院长姓名">
                <el-autocomplete
                  v-model="modalData.deanName"
                  placeholder="请输入院长姓名..."
                  value-key="label"
                  :trigger-on-focus="false"
                  :fetch-suggestions="queryTeachers"
                  @select="selectDean"
                />
              </el-form-item>
              <el-form-item label="院长工号">
                <el-input v-model="modalData.deanNo" :disabled="true" />
              </el-form-item>
              <el-form-item v-if="modalModel !== 'Look'">
                <el-button @click="modalCancelHandler">取消</el-button>
                <el-button type="primary" @click="modalSubmitHandler">提交</el-button>
              </el-form-item>
            </div>
          </el-tab-pane>
        </el-tabs>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import CrudView from '@/components/CrudView'
import { getTeacherDropDownByName } from '@/api/ms/dropdown'
import { getPage, getById, update, create, deleteByIds } from '@/api/ms/organization/org/college'
// vue对象钩子
let vueHook = null

function getDefaultModalData() {
  return { // 默认的学院信息编辑/新增modal框数据
    id: null,
    collegeName: '',
    address: '',
    telNumber: '',
    deanNo: '',
    deanName: ''
  }
}

export default {
  name: 'College',
  components: { CrudView },
  data() {
    return {
      viewLoading: false,
      formData: {
        collegeName: '',
        address: ''
      },
      dropDownData: {
        // 候选教师数据
        teacher: []
      },
      formItems: [
        { order: 1, label: '学院名称', type: 'Input', paramName: 'collegeName' },
        { order: 2, label: '学院地址', type: 'Input', paramName: 'address' },
        { order: 3, type: 'Button', btnName: '查询', clickHandler: () => {
          vueHook.ignoreRefresh = true
          vueHook.pageInfo.pageNum = 1
          vueHook.refreshPageList()
        }
        }
      ],
      btnItems: [
        { order: 1, name: '查看', type: 'primary', clickHandler: () => vueHook.openModal('Look') },
        { order: 2, name: '编辑', type: 'warning', clickHandler: () => vueHook.openModal('Edit') },
        { order: 3, name: '添加', type: 'success', clickHandler: () => vueHook.openModal('Create') },
        { order: 4, name: '删除', type: 'danger', clickHandler: () => vueHook.batchDeleteCollege() }
      ],
      pageColums: [
        { label: '学院名称', propName: 'collegeName' },
        { label: '学院地址', propName: 'address' },
        { label: '学院电话', propName: 'telNumber' },
        { label: '院长', propName: 'deanName', isLink: true, linkHanlder: (row) => { console.log(row.deanNo) } }
      ],
      pageInfo: {
        pageNum: 1, // 当前页
        pageSize: 10, // 每页行数
        total: 1000 // 列表总行数
      },
      selectionChangeHandler: (srows) => { // 记录选择改变handler
        vueHook.ids = srows.map(i => i.id)
      },
      list: [], // 数据列表
      ignoreRefresh: false,
      ids: [], // 选中的id列表
      showModal: false, // modal框显示标识
      modalTitle: '', // modal标题
      modalModel: 'Look', // modal状态 ，分别为 Look、Edit、Create
      activename: 'first',
      modalData: {} // 学院信息编辑/新增modal框数据
    }
  },
  computed: {
    // 分页参数组装
    pageParam() {
      const { collegeName, address } = this.formData
      const pageInfo = this.pageInfo
      return { collegeName, address, pageInfo }
    }
  },
  watch: {
    pageInfo: {
      handler(val) {
        if (this.ignoreRefresh) {
          // 需要忽略本次change
          this.ignoreRefresh = false
          return
        }
        // 向后台请求新的表格数据
        this.refreshPageList()
      },
      deep: true
    }
  },
  mounted() {
    // 暴露vue对象
    vueHook = this
    // 请求下拉框数据
    this.refreshDropDown()
    // 向后台请求新的表格数据
    this.refreshPageList()
  },
  methods: {
    // “院长姓名”表单域候选输入处理
    queryTeachers(qstr, callback) {
      if (!qstr || qstr.length === 0) {
        return
      }
      // 从后台查询匹配的教师信息列表
      getTeacherDropDownByName(qstr).then(({ data }) => {
        this.dropDownData.teacher = data
        callback(data)
      })
    },
    // "院长姓名"表单域候选选择处理
    selectDean(item) {
      this.modalData.deanNo = item.value
    },
    // 刷新表单下拉框数据
    refreshDropDown() {
      // 暂时没有需要请求的表单数据
    },
    // 刷新学院列表数据
    refreshPageList() {
      getPage(this.pageParam).then(({ list, pageInfo }) => {
        this.ignoreRefresh = true
        this.list = list
        this.pageInfo = pageInfo
      })
    },
    // 打开学院信息编辑/新增modal
    openModal(model) {
      // 如果是Create操作，直接打开modal
      if (model === 'Create') {
        // 打开modal
        this.modalTitle = '学院信息创建'
        this.modalModel = model
        this.showModal = true
        return
      }

      // 获取选中的学院id列表
      const ids = this.ids
      if (!ids || ids.length === 0) {
        this.$message.error('请选择一条记录')
        return
      }
      if (ids.length > 1) {
        this.$message.error('只能选择一条记录')
        return
      }
      // 获取学院详细信息 ，成功后打开modal
      getById(ids[0]).then(({ data }) => {
        this.modalData = data
        // 打开modal
        this.modalModel = model
        this.modalTitle = model === 'Edit' ? '学院信息编辑' : '学院信息详情'
        this.showModal = true
      })
    },
    // 关闭学院信息编辑/新增modal
    closeModal() {
      this.showModal = false
      // 重置modal数据
      this.activename = 'first'
      this.modalData = getDefaultModalData()
    },
    // 点击modal取消按钮
    modalCancelHandler() {
      this.closeModal()
    },
    // 点击modal提交按钮
    modalSubmitHandler() {
      if (this.modalModel === 'Edit') {
        this.updateCollegeInfo()
      } else if (this.modalModel === 'Create') { this.createCollegeInfo() }
    },
    // 创建学院信息
    createCollegeInfo() {
      create(this.modalData).then((res) => {
        this.$message.success(res.message)
        // 刷新数据
        this.refreshPageList()
        // 关闭modal
        this.closeModal()
      }).catch(err => {
        console.log(err)
        // 关闭modal
        this.closeModal()
      })
    },
    // 修改学院信息
    updateCollegeInfo() {
      update(this.modalData).then((res) => {
        this.$message.success(res.message)
        // 刷新数据
        this.refreshPageList()
        // 关闭modal
        this.closeModal()
      }).catch(err => {
        console.log(err)
        // 关闭modal
        this.closeModal()
      })
    },
    // 批量删除学院信息(逻辑删除)
    batchDeleteCollege() {
      if (this.ids === null || this.ids.length < 1) {
        this.$message.error('请至少选择一条记录')
        return
      }
      this.$confirm('请确认是否删除？').then(() => {
        deleteByIds(this.ids).then(res => {
          this.$message.success(res.message)
          // 刷新数据
          this.refreshPageList()
        }).catch(err => {
          console.log(err)
        })
      }).catch(() => {
        this.$message.info('删除已取消')
      })
    }

  }
}
</script>

<style>

</style>
